# -*- coding:utf-8 -*-

# @File     :cache
# @Author   :Yupeng
# @Date     :2018/11/12 19:41

from django.conf import settings
from enum import IntEnum
import time

'''

'''

conn = None
if not settings.DEBUG:
    import memcache

    conn = memcache.Client(['localhost:11211'])

_FULL_TEXT_LAST_UPDATED_KEY = '_hte_search_full_text_last_updated'
_TEMPLATE_LAST_UPDATED_KEY = '_hte_search_template_last_updated'


class CachedType(IntEnum):
    FULL_TEXT = 0
    TREE = 1
    CRITERION = 2


def set_full_text_cache(hashed_query, meta_id_list: list):
    if conn is None:
        return
    now = time.time()
    value = (CachedType.FULL_TEXT, now, meta_id_list)
    conn.set(str(hash(hashed_query)), value, 1800)


def get_full_text_cache(hashed_query):
    if conn is None:
        return
    value = conn.get(str(hash(hashed_query)))
    if value is None:
        return

    cached_type, last_time, meta_id_list = value
    if cached_type != CachedType.FULL_TEXT:
        return

    last_updated = conn.get(_FULL_TEXT_LAST_UPDATED_KEY)
    if last_updated:
        if last_updated > last_time:
            return  # 过期了
    return meta_id_list


def set_template_cache(hashed_query, template_id, meta_id_list):
    if conn is None:
        return
    now = time.time()
    value = (CachedType.TREE, now, template_id, meta_id_list)
    conn.set(str(hash(hashed_query)), value, 1800)

def get_template_cache(hashed_query):
    if conn is None:
        return
    value = conn.get(str(hash(hashed_query)))
    if value is None:
        return

    cached_type, last_time, template_id, meta_id_list = value
    if cached_type != CachedType.TREE:
        return
    last_updated = conn.get(_TEMPLATE_LAST_UPDATED_KEY + str(template_id))
    if last_updated:
        if last_updated > last_time:
            return  # 过期了
    return meta_id_list

def update_full_text_cache():
    if conn is None:
        return
    conn.set(_FULL_TEXT_LAST_UPDATED_KEY, time.time())

def update_template_cache(template_id_or_list):
    if conn is None:
        return
    if not isinstance(template_id_or_list, list):
        template_id_or_list = [template_id_or_list]
    now = time.time()
    [conn.set(_TEMPLATE_LAST_UPDATED_KEY + str(x), now) for x in template_id_or_list]
